<?php

namespace app\common\service;
use think\Db;
use \Translate\BaiduApi;
use \Translate\YoudaoApi;
class TranslateService{

	/*
	获取翻译后的内容
	 */
	public static function baiduApi($str,$lang='en'){
		if($lang == 'zh'){
			return $str;
		}
		// if($lang == 'yn'){
		// 	$lang = 'id';
		// }
		//缓存中获取
		$str_md5 = md5($str);
		$translate = cache($str_md5.'_translate_'.$lang);

			
		if(empty($translate)){
			//翻译接口获取
			if(mb_strlen($str) <= 1000){
				//数据库获取
				$translate = model('TranslateModel')->getTranslate($str_md5,$lang);
				if(empty($translate)){
					//翻译接口获取
					$translate = BaiduApi::translate($str,$lang);
					// $translate = YoudaoApi::translate($str,$lang);
					
					// var_dump($translate);die();
					//翻译成功
					if($translate != $str){
						//写入缓存
						cache($str_md5.'_translate_'.$lang,$translate);
						//写入数据库
						model('TranslateModel')->addData($str_md5,$str,$lang,$translate);
					}
				}
			} else {
				$translate = '';
				$num = ceil(mb_strlen($str)/1000);
				for ($i=0; $i < $num; $i++) { 
					$z_str = mb_substr($str, $i*1000,1000);
					$z_md5_str = md5($z_str);
					//数据库获取
					$z_trans_str = model('TranslateModel')->getTranslate($z_md5_str,$lang);
					if(empty($translate)){
						$z_trans_str = BaiduApi::translate($z_str,$lang);
						//翻译成功
						if($z_trans_str != $z_str){
							//写入数据库
							model('TranslateModel')->addData($z_md5_str,$z_str,$lang,$z_trans_str);

						}
					}
					$translate .= $z_trans_str;
				}
				if($translate != $str){
					//写入缓存
					cache($str_md5.'_translate_'.$lang,$translate);
				}
			}
		}
		return $translate;
	}
}